package com.hzt.system.controller;

import com.hzt.system.common.Constant;
import com.hzt.system.common.DataGridView;
import com.hzt.system.common.ResultObj;
import com.hzt.system.domain.Role;
import com.hzt.system.service.RoleService;
import com.hzt.system.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
*
*
* @Author:hzt
* @Date:8:54 下午 2020/7/15
*/
@RestController
@RequestMapping("api/role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @RequestMapping("loadAllRole")
    public DataGridView loadAllRole(RoleVo roleVo){
        return roleService.loadAllRole(roleVo);
    }


    //查询所有角色不分页
    @RequestMapping("loadAllAvailableRoleNoPage")
    public DataGridView loadAllAvailableRoleNoPage(RoleVo roleVo){
        roleVo.setAvailable(Constant.AVAILABLE_TRUE);
        return roleService.loadAllAvailableRoleNoPage(roleVo);
    }




    /**
     * 要放入缓存的
     *  @param role
     * @return
     */
    @PostMapping("addRole")
    public ResultObj addRole(Role role){
        try {
            role.setAvailable(Constant.AVAILABLE_TRUE);
            role.setCreatetime(new Date());
            this.roleService.saveRole(role);
            return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }

    //更新操作
    @RequestMapping("updateRole")
    public ResultObj updateRole(Role role){
        try {
            this.roleService.updateRole(role);
            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }


    //删除
    @RequestMapping("deleteRole")
    public ResultObj deleteRole(Role role){
        try {
            this.roleService.removeById(role.getId());
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }


    /**
     * 根据角色id查找权限和菜单
     * @param id
     * @return
     */
    @RequestMapping("queryMenuIdsByRid")
    public Object queryMenuIdsByRid(Integer id){
        List<Integer> mids = this.roleService.queryMenuIdsByRid(id);
        return new  DataGridView(mids);
    }


    /**
     * 保存角色和菜单之间的关系
     * @param rid
     * @param mids
     * @return
     */
    @RequestMapping("saveRoleMenu")
    public ResultObj saveRoleMenu(Integer rid,Integer[] mids){
        try {
            this.roleService.saveRoleMenu(rid,mids);
            return ResultObj.DISPATCH_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DISPATCH_ERROR;
        }
    }

}
